package progressBusiness;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import easyDAO.SqlDispatch;
import impl.TestServerBusinessImpl;
import models.MyConfig;
import models.ReturnJson;
import models.SqlReturnModel;
import tools.DDAlert;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Objects;

/**
 * Created by yangxianming on 2017/9/30.
 */
public class ShowProgress implements TestServerBusinessImpl {

    @Override
    public String doIt(HttpServletRequest request, MyConfig myConfig){
        ReturnJson returnJson = new ReturnJson();
        SqlDispatch sqlDispatch = new SqlDispatch(myConfig);
        JSONArray jsonArray = new JSONArray();
        String action = request.getParameter("action");

        if (Objects.equals("forFile", action)){
            //列出归档版本
            String year = request.getParameter("year");
            String progressName = request.getParameter("progressName");
            String sql = "SELECT progressname,isfiledetail,endtime,replay FROM progress WHERE isfile='1'";
            if (!Objects.equals(year, "")){
                sql = sql + " AND endtime LIKE '"+ year +"%'";
            }
            if (!Objects.equals(progressName, "")){
                sql = sql + " AND progressname LIKE '"+ progressName +"%'";
            }
            sql = sql + " ORDER BY endtime DESC";
            SqlReturnModel sqlReturnModel = sqlDispatch.selectWord(sql);
            returnJson.setResult(sqlReturnModel.getSelectReturnDataAsJsonArray());
            returnJson.setApiStatus((sqlReturnModel.getIsSuccess()) ? 1 : 0);
            returnJson.setErrorMsg(sqlReturnModel.getFailingReason());
        }

        if (Objects.equals("forWeb", action)){
            String sql = "SELECT id,progressname,detail FROM progress WHERE isfile = 2";
            SqlReturnModel sqlReturnModel = sqlDispatch.selectWord(sql);
            ArrayList<ArrayList<String>> progressList = sqlReturnModel.getSelectReturnData();

            for (ArrayList<String> line: progressList){
                JSONObject progressJson = new JSONObject();
                progressJson.put("id", line.get(0));
                progressJson.put("progressname", line.get(1));
                progressJson.put("detail", couProportion(line.get(2)).toString());
                jsonArray.add(progressJson);
            }
            returnJson.setResult(jsonArray);
            returnJson.setApiStatus((sqlReturnModel.getIsSuccess()) ? 1 : 0);
            returnJson.setErrorMsg(sqlReturnModel.getFailingReason());
        }

        if (Objects.equals("forMobile", action)){
            //预览按钮展示必要信息，钉钉推送也使用
            String id = request.getParameter("id");
            String sqlId = "";
            if (!Objects.equals("", id)){
                sqlId = " and id=" + id;
            }
            String sql = "SELECT id,progressname,detail FROM progress WHERE isfile = 2" + sqlId;
            SqlReturnModel sqlReturnModel = sqlDispatch.selectWord(sql);
            ArrayList<ArrayList<String>> progressList = sqlReturnModel.getSelectReturnData();

            JSONObject redata = new JSONObject();
            if (progressList.size() == 0){
                //没有的项目或者已经归档
                returnJson.setResult("项目已经测试完毕并归档，需要查看历史记录请咨询小明");
                returnJson.setApiStatus(2);
                returnJson.setErrorMsg(sqlReturnModel.getFailingReason());
            }else {
                JSONObject progressJson = new JSONObject();
                redata = couModuleProportion(progressList.get(0).get(2));
                progressJson.put("totalProportion", redata.getString("totalProportion"));
                progressJson.put("progressname", progressList.get(0).get(1));
                progressJson.put("detail", redata.getString("detail"));
                returnJson.setResult(progressJson);
                returnJson.setApiStatus((sqlReturnModel.getIsSuccess()) ? 1 : 0);
                returnJson.setErrorMsg(sqlReturnModel.getFailingReason());
            }

            //是否推送钉钉
            String isDD = request.getParameter("dd");
            if (Objects.equals("1", isDD)){
                String domain = myConfig.getPropertiesConfig().getProperties().getProperty("domain");
                String port = myConfig.getPropertiesConfig().getProperties().getProperty("port");
                //yxm.vaiwan.com        10.10.28.42:1985
//                String reportPage = "http://10.10.28.42:1985/html/progressmobile.html?id="+id;
                String reportPage = "http://"+domain+port+"/html/progressmobile.html?id="+id;
                String information = "设计用例:"+redata.getString("designCase")+" ; 执行用例:"+redata.getString("runCase")+"\n";
                information = information + "提交问题:"+redata.getString("submitBug")+" ; 修复问题:"+redata.getString("closeBug");
                String ddTitle = "[mu]"+progressList.get(0).get(1)+"-测试进度 "+redata.getString("totalProportion")+"%";
                String[] message = {information, ddTitle, "", reportPage};
                DDAlert ddAlert = new DDAlert();
                ddAlert.send("link", "url3", message, "13564324375");
            }
        }



        return returnJson.toString();
    }

    private JSONArray couProportion(String json){
        //计算每条的百分比
        JSONArray ja = JSON.parseArray(json);
        for (int i=0; i<ja.size(); i++){
            JSONArray one = ja.getJSONArray(i);
            double v1 = Double.valueOf(Objects.equals("", String.valueOf(one.get(5))) ? "0" : String.valueOf(one.get(5)));
            double v2 = Double.valueOf(Objects.equals("",String.valueOf(one.get(6))) ? "0" : String.valueOf(one.get(6)));
            double v3 = Double.valueOf(Objects.equals("",String.valueOf(one.get(7))) ? "0" : String.valueOf(one.get(7)));
            double v4 = Double.valueOf(Objects.equals("",String.valueOf(one.get(8))) ? "0" : String.valueOf(one.get(8)));
            DecimalFormat df = new DecimalFormat("######0.00");
            String proportion = "0";
            if ((v1+v3) != 0.00){
                proportion = String.valueOf(df.format((v2+v4)/(v1+v3)*100));
            }
            one.set(9, proportion);
            ja.set(i, one);
        }
        return ja;
    }

    private JSONObject couModuleProportion(String json){
        JSONObject reJson = new JSONObject();
        //计算每条的百分比
        JSONArray array = new JSONArray();
        JSONArray ja = JSON.parseArray(json);
        double molecule = 0.0;
        double denominator = 0.0;
        int designCase = 0;
        int runCase = 0;
        int submitBug = 0;
        int closeBug = 0;
        for (int i=0; i<ja.size(); i++){
            JSONArray refineOne = new JSONArray();
            JSONArray one = ja.getJSONArray(i);
//            System.out.println(one);
            Double v1 = Double.valueOf(Objects.equals("", String.valueOf(one.get(5))) ? "0" : String.valueOf(one.get(5)));
            Double v2 = Double.valueOf(Objects.equals("",String.valueOf(one.get(6))) ? "0" : String.valueOf(one.get(6)));
            Double v3 = Double.valueOf(Objects.equals("",String.valueOf(one.get(7))) ? "0" : String.valueOf(one.get(7)));
            Double v4 = Double.valueOf(Objects.equals("",String.valueOf(one.get(8))) ? "0" : String.valueOf(one.get(8)));
            molecule = molecule + v2 + v4;
            denominator = denominator + v1 + v3;
            refineOne.add(one.get(0)+"-"+one.get(1));
            refineOne.add(one.get(4));
            refineOne.add(one.get(3));
            refineOne.add(one.get(9));
            refineOne.add(one.get(10));
            array.add(refineOne);
            designCase = designCase + v1.intValue();
            runCase = runCase + v2.intValue();
            submitBug = submitBug + v3.intValue();
            closeBug = closeBug + v4.intValue();
        }

        DecimalFormat df = new DecimalFormat("######0.00");
        String totalProportion = "0";
        if (denominator != 0.00){
            totalProportion = String.valueOf(df.format(molecule/denominator*100));
        }
        reJson.put("totalProportion", totalProportion);
        reJson.put("detail", array);
        reJson.put("designCase", designCase);
        reJson.put("runCase", runCase);
        reJson.put("submitBug", submitBug);
        reJson.put("closeBug", closeBug);
        return reJson;
    }
}
